package com.gzy.net_app.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.gzy.net_app.adapter.ImageInfoAdapter;
import com.gzy.net_app.api.ApiService;
import com.gzy.net_app.application.AppContext;
import com.gzy.net_app.bean.ImageInfo;
import com.gzy.net_app.databinding.FragmentHomeBinding;
import com.gzy.net_app.ui.BaseFragment;
import com.gzy.net_app.ui.activity.OneImageInfoActivity;
import com.gzy.network.NetworkApi;
import com.gzy.network.observer.BaseObserver;
import com.gzy.network.utils.KLog;
import com.orhanobut.hawk.Hawk;
import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseFragment<FragmentHomeBinding> {

  public static final String TAG = HomeFragment.class.getSimpleName();

  private ImageInfoAdapter imageInfoAdapter;
  List<ImageInfo> mImageInfos = new ArrayList<>();

  @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    imageInfoAdapter = new ImageInfoAdapter(requireContext());

    initData();
  }

  private void initData() {

    binding.recyclerview.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
    binding.recyclerview.setAdapter(imageInfoAdapter);
    getAllImageInfo();

    binding.swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override public void onRefresh() {
        binding.swipeRefresh.setRefreshing(true);
        getAllImageInfo();
      }
    });

    imageInfoAdapter.setOnItemClickLitener(new ImageInfoAdapter.OnItemClickLitener() {
      @Override public void onItemClick(int position) {
        Log.d(TAG,"点击了"+position);
        Intent intent = new Intent(requireContext(), OneImageInfoActivity.class);
        intent.putExtra("imageInfoId",mImageInfos.get(position).getId());
        startActivity(intent);
      }
    });
  }

  private void getAllImageInfo() {
    NetworkApi.createService(ApiService.class)
        .getAllImageInfoApi("" + Hawk.get("token"))
        .compose(NetworkApi.applySchedulers(new BaseObserver<List<ImageInfo>>() {
          @Override
          public void onSuccess(List<ImageInfo> imageInfos) {
            mImageInfos = imageInfos;
            imageInfoAdapter.updateImageInfoList(imageInfos);
            KLog.d(TAG, "所有作品：:" + imageInfos.toString());

            binding.swipeRefresh.setRefreshing(false);
          }

          @Override
          public void onFailure(Throwable e) {
            AppContext.showToast("访问失败");
            KLog.d(TAG, "访问失败");
            KLog.e(TAG, e.toString());

            binding.swipeRefresh.setRefreshing(false);
          }
        }));
  }

}